package com.etennis.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.etennis.constants.AppHttpCodeEnum;
import com.etennis.constants.IOEnum;
import com.etennis.exception.SystemException;
import com.etennis.mapper.CommodityMapper;
import com.etennis.pojos.PageResult;
import com.etennis.pojos.dto.web.GoodDTO;
import com.etennis.pojos.dto.web.GoodPageQueryDTO;
import com.etennis.pojos.entity.Commodity;
import com.etennis.pojos.vo.web.GoodVO;
import com.etennis.service.ICommodityService;
import com.etennis.utils.BeanCopyUtils;
import com.etennis.utils.IOUtils;
import com.etennis.utils.PageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class CommodityServiceImpl extends ServiceImpl<CommodityMapper, Commodity> implements ICommodityService {
    @Autowired
    CommodityMapper commodityMapper;
    @Autowired
    IOUtils ioUtils;

    @Override
    public void saveGood(GoodDTO goodDTO) {
        Commodity commodity = BeanCopyUtils.copyBean(goodDTO, Commodity.class);
        if(ioUtils.getType(goodDTO.getPicture().getOriginalFilename())!="0")
            throw  new SystemException(AppHttpCodeEnum.MEDIA_TYPE_ERROR);
        try {
            String url = ioUtils.uploadMedia(goodDTO.getPicture(), IOEnum.IS_COMMODITY);
            commodity.setUrl(url);
            commodity.setUploadTime(new Date());
            commodity.setStatus("0");
            commodityMapper.insert(commodity);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void updateGood(GoodDTO goodDTO) {
        Commodity commodity = BeanCopyUtils.copyBean(goodDTO, Commodity.class);
        commodityMapper.updateById(commodity);
    }

    @Override
    public PageResult<GoodVO> pageGood(GoodPageQueryDTO pageQueryDTO) {
        Page page = PageUtil.convert(pageQueryDTO);
        LambdaQueryWrapper<Commodity> wrapper=new LambdaQueryWrapper<Commodity>()
                .like(pageQueryDTO.getName()!=null,Commodity::getName,pageQueryDTO.getName());

        Page<Commodity> goodPage = commodityMapper.selectPage(page, wrapper);
        PageResult<GoodVO> res = PageUtil.convert(goodPage, GoodVO.class);
        return res;
    }
}
